package com.zj.gencode.config;

import com.alibaba.fastjson.JSON;
import com.zj.gencode.exception.GenException;
import com.zj.util.utils.StringUtil;
import lombok.Getter;
import lombok.Setter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 配置信息
 *
 * @author xi.yang
 * @create 2018-10-16 15:40
 **/
@Getter@Setter
public class GenConfig {
    private static final String fileOutPathName = "file.out.path";
    private static final String fileExcelPathName = "file.excel.path";
    private static final String toPathName = "object.to.package";
    private static final String daoPathName = "object.dao.package";
    private String fileOutPath;
    private String fileExcelPath;
    private String toPackage;
    private String daoPackage;

    public static GenConfig getInstance() {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File(getPropertiesFilePath())));
        } catch (IOException e) {
            throw new GenException("获取配置文件错误！请检查配置文件application.properties是否在resources目录下！");
        }
        GenConfig genConfig = new GenConfig();
        final String fileOutPath = properties.getProperty(fileOutPathName);
        if (StringUtil.isBlank(fileOutPath)) {
            throw new GenException("请配置文件输出位置");
        }
        genConfig.setFileOutPath(fileOutPath);
        final String excelPath = properties.getProperty(fileExcelPathName);
        if (StringUtil.isBlank(excelPath)) {
            throw new GenException("请配置excel文件位置");
        }
        genConfig.setFileExcelPath(excelPath);
        final String toPackage = properties.getProperty(toPathName);
        if (StringUtil.isBlank(toPackage)) {
            throw new GenException("请配置TO类的包名");
        }
        genConfig.setToPackage(toPackage);
        final String daoPackage = properties.getProperty(daoPathName);
        if (StringUtil.isBlank(daoPackage)) {
            genConfig.setDaoPackage(toPackage+".dao");
        } else {
            genConfig.setDaoPackage(daoPackage);
        }
        return genConfig;
    }

    private static String getPropertiesFilePath() {
        return new File("").getAbsolutePath() + File.separator+"src"+File.separator+"main"+File.separator + "resources" + File.separator + "application.properties";
    }
}
